import React, {
  useImperativeHandle,
  //useRef,
  forwardRef,
  useState,
} from 'react';
import { Text, StyleSheet, Platform, View } from 'react-native';
import {
  InputItem,
  Modal,
  List,
  Checkbox,
  Radio,
  Toast,
  ActivityIndicator,
  Button,
  Flex,
} from '@ant-design/react-native';
import RnBarcodeScanner from '../../aerialMaterial/components/rnBarcodeScanner';

const styles = StyleSheet.create({
  inputItemUnderline: {
    borderBottomWidth: 1,
    borderBottomColor: '#bbb',
  },
  modalPosition: {
    position: 'relative',
    bottom: Platform.isPad ? 200 : 0,
  },
});

function JobCardItemGatherModal({ onOk, onCancel }, ref) {
  const [visible, setVisible] = useState(false);
  const [scanVisible, setScanVisible] = useState(false);
  const [confirming, setConfirming] = useState(false);
  const [gatherItem, setGatherItem] = useState({
    textNodes: [],
    editType: '', // radio checkbox select text
    editOptions: [], // value label checked
    editResult: '',
  });
  useImperativeHandle(ref, () => ({
    show: (texts, editType, options, editText) => {
      console.log(texts, editType, options, editText);
      setGatherItem({
        textNodes: texts,
        editType,
        editOptions: options,
        editResult: editText,
      });
      handleVisibleFlip();
    },
    hide: handleVisibleFlip,
  }));

  const handleVisibleFlip = () => {
    setVisible(!visible);
  };
  const handleChange = (val) => {
    setGatherItem({ ...gatherItem, editResult: val });
  };
  const handleRadioChange = (edOpt, checked) => {
    setGatherItem({
      ...gatherItem,
      editOptions: gatherItem.editOptions.map((edo) => {
        if (edo.value === edOpt.value) {
          return { ...edo, checked };
        } else if (edo.checked) {
          return { ...edo, checked: false };
        }
        return edo;
      }),
    });
  };
  const handleCheckChange = (edOpt, checked) => {
    setGatherItem({
      ...gatherItem,
      editOptions: gatherItem.editOptions.map((edo) => {
        if (edo.value === edOpt.value) {
          return { ...edo, checked };
        }
        return edo;
      }),
    });
  };
  let editComp;
  switch (gatherItem.editType) {
    case 'radio':
    case 'select':
      editComp = gatherItem.editOptions.map((edo) => (
        <Radio.RadioItem
          key={edo.value}
          checked={edo.checked}
          onChange={(ev) => handleRadioChange(edo, ev.target.checked)}
        >
          {edo.label}
        </Radio.RadioItem>
      ));
      break;
    case 'checkbox':
      editComp = gatherItem.editOptions.map((edo) => (
        <Checkbox.CheckboxItem
          key={edo.value}
          checked={edo.checked}
          onChange={(ev) => handleCheckChange(edo, ev.target.checked)}
        >
          {edo.label}
        </Checkbox.CheckboxItem>
      ));
      break;
    default:
      editComp = (
        <View>
          <InputItem
            autoFocus
            value={gatherItem.editResult}
            onChange={handleChange}
            style={styles.inputItemUnderline}
          />
          <Button
            type="primary"
            size="small"
            onPress={() => {
              setScanVisible(true);
            }}
          >
            扫码识别
          </Button>
          <Modal visible={scanVisible}>
            <RnBarcodeScanner
              onBarCodeRead={(barcode) => {
                console.log(barcode);
                setGatherItem({ ...gatherItem, editResult: barcode });
              }}
              onExitScan={() => {
                setScanVisible(false);
              }}
            />
          </Modal>
        </View>
      );
      break;
  }
  return (
    <Modal
      visible={visible}
      transparent
      style={styles.modalPosition}
      footer={[
        {
          text: '取消',
          onPress: () => {
            if (onCancel) {
              onCancel();
            }
            handleVisibleFlip();
          },
        },
        {
          text: (
            <>
              <ActivityIndicator animating={confirming} />
              <Text>确定</Text>
            </>
          ),
          onPress: async () => {
            if (confirming) {
              return;
            }
            if (onOk) {
              setConfirming(true);
              let editResults = gatherItem.editResult;
              if (!editResults) {
                console.log(editResults);
                editResults = gatherItem.editOptions.filter(
                  (edo) => edo.checked,
                );
                // if (!editResults.length) {
                //   Toast.fail('必须至少选择一项');
                //   return;
                // }
                if (gatherItem.editType === 'checkbox') {
                  editResults = gatherItem.editOptions;
                }
              }
              await onOk(editResults);
              setConfirming(false);
            }
            handleVisibleFlip();
          },
        },
      ]}
    >
      <List>
        <InputItem value={gatherItem.textNodes[0]} editable={false} />
        {editComp}
        {gatherItem.textNodes.length === 2 && (
          <InputItem value={gatherItem.textNodes[1]} editable={false} />
        )}
      </List>
    </Modal>
  );
}

export default forwardRef(JobCardItemGatherModal);
